package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.ServiceReservation;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.ServiceType;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetServiceService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/service")
@Tag(name = "宠物服务管理模块")
public class PetServiceController {

    @Autowired
    private PetServiceService petServiceService;

    @Autowired
    private UserService userService;

    @Operation(summary = "查询宠物服务项目列表（洗澡、美容、训练等）")
    @GetMapping("/list")
    public Result<List<ServiceType>> getServiceTypeList() {
        try {
            List<ServiceType> list = petServiceService.getServiceTypeList();
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询服务类型列表失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(summary = "查看单项服务详情")
    @GetMapping("/detail/{id}")
    public Result<ServiceType> getServiceTypeDetail(
            @Parameter(description = "服务类型ID") @PathVariable Long id) {
        try {
            ServiceType serviceType = petServiceService.getServiceTypeById(id);
            if (serviceType != null) {
                return Result.success(serviceType);
            }
            return Result.error("服务不存在");
        } catch (Exception e) {
            log.error("查询服务详情失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(summary = "用户预约宠物服务")
    @PostMapping("/reserve")
    public Result<ServiceReservation> reserveService(@RequestBody ServiceReservation reservation) {
        try {
            log.info("收到服务预约请求 - serviceTypeId: {}, petId: {}, reservationDate: {}, reservationTime: {}, totalAmount: {}", 
                    reservation.getServiceTypeId(), reservation.getPetId(), 
                    reservation.getReservationDate(), reservation.getReservationTime(),
                    reservation.getTotalAmount());
            
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            reservation.setUserId(user.getId());
            
            // 参数验证日志
            if (reservation.getServiceTypeId() == null) {
                log.error("参数验证失败：缺少 serviceTypeId");
                return Result.error("参数不完整：缺少服务类型ID");
            }
            if (reservation.getPetId() == null) {
                log.error("参数验证失败：缺少 petId");
                return Result.error("参数不完整：缺少宠物ID");
            }
            
            boolean success = petServiceService.reserveService(reservation);
            if (success) {
                log.info("预约成功 - userId: {}, serviceTypeId: {}, petId: {}, totalAmount: {}", 
                        user.getId(), reservation.getServiceTypeId(), reservation.getPetId(), 
                        reservation.getTotalAmount());
                return Result.success("预约成功", reservation);
            } else {
                return Result.error("预约失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("参数验证异常: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("预约服务失败", e);
            return Result.error("预约失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询宠物的服务预约记录")
    @GetMapping({"/reserves", "/my-reserves"})
    public PageResult<ServiceReservation> getReservationList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物ID") @RequestParam(required = false) Long petId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return PageResult.pageError("用户不存在");
            }

            IPage<ServiceReservation> page = petServiceService.getReservationList(user.getId(), petId, pageNum, pageSize);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询预约记录失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "管理员确认预约")
    @PutMapping("/reserve/confirm/{id}")
    public Result<?> confirmReservation(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            boolean success = petServiceService.confirmReservation(id);
            return success ? Result.success("确认成功") : Result.error("确认失败");
        } catch (Exception e) {
            log.error("确认预约失败", e);
            return Result.error("确认失败: " + e.getMessage());
        }
    }

    @Operation(summary = "标记服务已完成")
    @PutMapping("/reserve/finish/{id}")
    public Result<?> finishReservation(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            boolean success = petServiceService.finishReservation(id);
            return success ? Result.success("标记成功") : Result.error("标记失败");
        } catch (Exception e) {
            log.error("标记服务完成失败", e);
            return Result.error("标记失败: " + e.getMessage());
        }
    }

    @Operation(summary = "用户取消预约")
    @DeleteMapping("/reserve/cancel/{id}")
    public Result<?> cancelReservation(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = petServiceService.cancelReservation(id, user.getId());
            return success ? Result.success("取消成功") : Result.error("取消失败");
        } catch (Exception e) {
            log.error("取消预约失败", e);
            return Result.error("取消失败: " + e.getMessage());
        }
    }

    @Operation(summary = "检查预约时间可用性")
    @GetMapping("/check-availability")
    public Result<?> checkAvailability(
            @Parameter(description = "服务类型ID") @RequestParam Long serviceTypeId,
            @Parameter(description = "预约时间") @RequestParam String reservationDate) {
        try {
            java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(reservationDate);
            boolean available = petServiceService.checkAvailability(serviceTypeId, dateTime);
            return Result.success("查询成功", available);
        } catch (Exception e) {
            log.error("检查时间可用性失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取可预约时间段")
    @GetMapping("/available-times")
    public Result<?> getAvailableTimes(
            @Parameter(description = "服务类型ID") @RequestParam Long serviceTypeId,
            @Parameter(description = "日期(YYYY-MM-DD)") @RequestParam String date) {
        try {
            var times = petServiceService.getAvailableTimes(serviceTypeId, date);
            return Result.success(times);
        } catch (Exception e) {
            log.error("获取可预约时间段失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户预约历史")
    @GetMapping("/my-history")
    public PageResult<ServiceReservation> getMyHistory(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return PageResult.pageError("用户不存在");
            }

            IPage<ServiceReservation> page = petServiceService.getMyHistory(user.getId(), pageNum, pageSize);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("获取预约历史失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }
}
